// Vuex 购物车 store 空间名 Day7Shoppin
// 导入 Day4 的 axios
import axios from '@/views/Day/Day4/views/ShoppingTrolley/axios.js'
export default {
  // 开启命名空间
  namespaced: true,
  state: () => ({
    cart: []
  }),
  actions: {
    // 定义 ajax 请求 函数
    async getCartList(context) {
      const { data: res } = await axios.get('/api/cart')
      context.commit('updateCart', res.list)
    }
  },
  mutations: {
    // 更新 cart
    updateCart(state, payload) {
      state.cart = payload
    },
    // 更新商品个数
    updateCount(state, payload) {
      const index = state.cart.findIndex(obj => obj.id === payload.id)
      state.cart[index].goods_count = payload.value
    },
    // 更新商品状态
    updateState(state, payload) {
      const index = state.cart.findIndex(obj => obj.id === payload.id)
      state.cart[index].goods_state = payload.value
    },
    // 全选状态影响 小选
    updateIsAllState(state, payload) {
      state.cart.forEach(item => (item.goods_state = payload))
    }
  },
  getters: {
    // 全选状态
    isAllState(state) {
      return state.cart.every(item => item.goods_state)
    },
    // 勾选状态的总价格
    isAllPrice(state) {
      return state.cart
        .filter(item => item.goods_state)
        .reduce((acc, val) => acc + val.goods_price * val.goods_count, 0)
    },
    // 结算总个数
    isAllCount(state) {
      return state.cart
        .filter(item => item.goods_state)
        .reduce((acc, val) => acc + val.goods_count, 0)
    }
  }
}
